<?php

class CatalogController extends Zend_Controller_Action
{

    /**
    * @var Cms_Model_Catalog
    */
    protected $_catalogModel;

    /**
    * @var array
    */
    protected $_forms = array();

    /**
    * @var Zend_Controller_Action_Helper_Url
    */
    protected $_urlHelper;

    public function init()
    {
        $this->_catalogModel = new Cms_Model_Catalog();

        $this->_urlHelper = $this->_helper->getHelper('url');
    }

    public function categoryAction()
    {
            $action = $this->_getParam('do');

            switch($action){

                case 'insert':

                    $this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'catalogCategory', true);
                    
                    $this->view->categoryForm = $this->_getCategoryForm();

                    $request = $this->getRequest();

                     if($request->isPost()){
                          if (!$this->_forms['categoryForm']->isValid($request->getPost())) {
                                    return $this->render('savecategory');
                            }

                            $this->_catalogModel->saveCategory($this->_forms['categoryForm']->getValues());
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Category has been successfully created!");
                            $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogCategory', true);
                        }
                    
                    $this->_helper->viewRenderer('savecategory');
                    break;

                case 'update':

                    $this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'catalogCategory', true);

                    $categoryId = (int) $this->_getParam('id');

                    //if category id does not exists - redirect to category access
                    $categoryInfo = $this->_catalogModel->getCategoryById($categoryId);
                    if((null === $categoryInfo)){
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogCategory', true);
                    }

                    $this->view->categoryForm = $this->_getCategoryForm('update', $categoryId);

                    $request = $this->getRequest();

                    if($request->isPost()){
                          if (!$this->_forms['categoryForm']->isValid($request->getPost())) {
                                    return $this->render('savecategory');
                            }

                            $this->_catalogModel->saveCategory($this->_forms['categoryForm']->getValues(), $categoryInfo);
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Category has been successfully updated!");
                            $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogCategory', true);
                        }

                    $this->view->categoryForm->populate($categoryInfo->toArray());

                    $this->_helper->viewRenderer('savecategory');

                    break;
                    
                case 'delete':

                    if($this->getRequest()->isPost()){

                        $categories = $this->_getParam('selected');

                        if ((!empty($categories) && (is_array($categories)))) {
                                $countError = 0;
                                foreach ($categories as $category) {
                                        //check if any product has been assigned to the category
                                        if(($this->_catalogModel->getProductsByCategory($category, null, false)->count() > 0)){
                                               $countError += 1;
                                        }else{
                                            //reset the category children parentID to zero(0)
                                            $categoryChildren = $this->_catalogModel->getCategoriesByParentId($category);
                                            if(($categoryChildren->count() > 0)){
                                                foreach ($categoryChildren as $categoryChild) {
                                                    $categoryChild->parentId = 0;
                                                    $this->_catalogModel->saveCategory($categoryChild->toArray(), $categoryChild);
                                                }
                                            }
                                            //delete category
                                            $this->_catalogModel->deleteCategory(
                                                    $this->_catalogModel->getCategoryById($category));
                                        }
                                }

                                if($countError > 0){
                                        $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->addMessage("Warning: $countError category(s) cannot be deleted as it is currently assigned to a product(s)!");
                                    }else{
                                        $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Category(s) has been successfully deleted!");
                                    }
                        }

                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogCategory', true);

                    }else{
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogCategory', true);
                        }

                    break;
    
                case 'access':
                default:

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->hasMessages()) {
                            $this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->getMessages();
                        }

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageWarning')->hasMessages()) {
                            $this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->getMessages();
                        }

                    $this->view->categories = $this->_catalogModel->getCategories();
                    $this->_helper->viewRenderer('listcategory');
                    break;
            }
            
    }

    public function productAction()
    {

            $action = $this->_getParam('do');

            switch($action){

                case 'insert':

                    $this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'catalogProduct', true);

                    $this->view->productForm = $this->_getProductForm();

                    $request = $this->getRequest();

                     if($request->isPost()){
                          if (!$this->_forms['productForm']->isValid($request->getPost())) {
                                    return $this->render('saveproduct');
                            }

                            $this->_catalogModel->saveProduct($this->_forms['productForm']->getValues());
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Product has been successfully created!");
                            $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogProduct', true);
                        }

                    $this->_helper->viewRenderer('saveproduct');
                    break;

                case 'update':

                    $this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'catalogProduct', true);

                    $productId = (int) $this->_getParam('id');

                    //if product id does not exists - redirect to product access
                    $productInfo = $this->_catalogModel->getProductById($productId);
                    if((null === $productInfo)){
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogProduct', true);
                    }

                    $this->view->productForm = $this->_getProductForm('update',$productId);

                    $request = $this->getRequest();

                    if($request->isPost()){
                          if (!$this->_forms['productForm']->isValid($request->getPost())) {
                                    return $this->render('saveproduct');
                            }

                            $this->_catalogModel->saveProduct($this->_forms['productForm']->getValues(), $productInfo);
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Product has been successfully updated!");
                            
                            if(null !== $this->_helper->redirectUrl()){
                                $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                              }else{
                                   $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogProduct', true);
                                  }
                        }

                    $this->view->productForm->populate($productInfo->toArray());

                    $this->_helper->viewRenderer('saveproduct');

                    break;

               
                case 'delete':

                    if($this->getRequest()->isPost()){

                        $products = $this->_getParam('selected');

                        if ((!empty($products) && (is_array($products)))) {
                                $countError = 0;
                                foreach ($products as $product) {
                                        //check if an inventory has been created with the product
                                        $inventoryModel = new Cms_Model_Inventory();
                                        if(($inventoryModel->getTotalInventoryByProductId($product) > 0)){
                                               $countError += 1;
                                        }else{
                                            //delete product
                                            $this->_catalogModel->deleteProduct(
                                                    $this->_catalogModel->getProductById($product));
                                        }
                                }

                                if($countError > 0){
                                        $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->addMessage("Warning: $countError product(s) cannot be deleted as it is currently assigned to an inventory(s)!");
                                    }else{
                                        $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Product(s) has been successfully deleted!");
                                    }
                        }

                        if(null !== $this->_helper->redirectUrl()){
                                $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogProduct', true);
                                }

                    }else{
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogProduct', true);
                        }

                    break;

                case 'access':
                default:

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->hasMessages()) {
                            $this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->getMessages();
                        }

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageWarning')->hasMessages()) {
                            $this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->getMessages();
                        }

                    $data = array();
                    $partHeadUrl = '';
                    $partPaginationUrl = '';

                    if ($this->_getParam('sort')) {
                            $data['sort'] = $this->_getParam('sort');
                            $partPaginationUrl .= '&sort=' . $this->_getParam('sort');

                            if ($this->_getParam('order')) {
                                $data['order'] = $this->_getParam('order');
                                $partPaginationUrl .= '&order=' . $this->_getParam('order');
                            }else{
                                $data['order'] = 'asc';
                                $partPaginationUrl .= '&order=asc';
                            }
                    }

                    $partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';

                    if ($this->_getParam('page')){
                            $data['page'] = intval($this->_getParam('page'));
                            $partHeadUrl .= '&page=' . intval($this->_getParam('page'));
                    }else{ //turn on pagination by default
                        $data['page'] = 1; 
                    }

                    if ($this->_getParam('limit')) {
                            $data['limit'] = (int) $this->_getParam('limit');
                            $partHeadUrl .= '&limit=' . $this->_getParam('limit');
                            $partPaginationUrl .= '&limit=' . $this->_getParam('limit');
                    }

                    if ($this->_getParam('search')) {
                            $data['search'] = $this->_getParam('search');
                            $partHeadUrl .= '&search=' . $this->_getParam('search');
                            $partPaginationUrl .= '&search=' . $this->_getParam('search');
                    }

                    $this->view->data = $data;
                    $this->view->partHeadUrl = $partHeadUrl;
                    $this->view->partPaginationUrl = $partPaginationUrl;
                    
                    $this->view->products = ($this->_catalogModel->getProductsByCategory(0,$data)->count() > 0) ? $this->_catalogModel->getProductsByCategory(0,$data) : null;
                    $this->_helper->viewRenderer('listproduct');
                    break;
            }
    }

    public function supplierAction()
    {
        $action = $this->_getParam('do');

            switch($action){

                case 'insert':
                    
                    $this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'catalogSupplier', true);
                    
                    $this->view->supplierForm = $this->_getSupplierForm();

                    $request = $this->getRequest();

                     if($request->isPost()){
                          if (!$this->_forms['supplierForm']->isValid($request->getPost())) {
                                    return $this->render('savesupplier');
                            }

                            $this->_catalogModel->saveSupplier($this->_forms['supplierForm']->getValues());
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Supplier has been successfully created!");
                            $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogSupplier', true);
                        }
                    
                    $this->_helper->viewRenderer('savesupplier');
                    break;

                case 'update':

                    $supplierId = (int) $this->_getParam('id');

                    $this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'catalogSupplier', true);

                    //if supplier id does not exists - redirect to supplier access
                    $supplierInfo = $this->_catalogModel->getSupplierById($supplierId);
                    if((null === $supplierInfo)){
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogSupplier', true);
                    }

                    $this->view->supplierForm = $this->_getSupplierForm('update', $supplierId);

                    $request = $this->getRequest();

                    if($request->isPost()){
                          if (!$this->_forms['supplierForm']->isValid($request->getPost())) {
                                    return $this->render('savesupplier');
                            }

                            $this->_catalogModel->saveSupplier($this->_forms['supplierForm']->getValues(), $supplierInfo);
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Supplier has been successfully updated!");
                            
                            if(null !== $this->_helper->redirectUrl()){
                                    $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogSupplier', true);
                                }
                        }

                    $this->view->supplierForm->populate($supplierInfo->toArray());

                    $this->_helper->viewRenderer('savesupplier');

                    break;

               case 'delete':

                    if($this->getRequest()->isPost()){

                        $suppliers = $this->_getParam('selected');

                        if ((!empty($suppliers) && (is_array($suppliers)))) {
                                $countError = 0;
                                $inventoryModel = new Cms_Model_Inventory();
                                foreach ($suppliers as $supplier) {
                                        //check if an inventory has been created with the supplier
                                        if(($inventoryModel->getTotalInventoryBySupplierId($supplier) > 0)){
                                               $countError += 1;
                                        }else{
                                            //delete supplier
                                            $this->_catalogModel->deleteSupplier(
                                                    $this->_catalogModel->getSupplierById($supplier));
                                        }
                                }

                                if($countError > 0){
                                        $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->addMessage("Warning: $countError supplier(s) cannot be deleted as it is currently assigned to an inventory(s)!");
                                    }else{
                                        $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Supplier(s) has been successfully deleted!");
                                    }
                        }

                        if(null !== $this->_helper->redirectUrl()){
                                $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogSupplier', true);
                                }

                    }else{
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogSupplier', true);
                        }

                    break;

                case 'access':
                default:

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->hasMessages()) {
                            $this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->getMessages();
                        }

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageWarning')->hasMessages()) {
                            $this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->getMessages();
                        }

                    $data = array();
                    $partHeadUrl = '';
                    $partPaginationUrl = '';

                    if ($this->_getParam('sort')) {
                            $data['sort'] = $this->_getParam('sort');
                            $partPaginationUrl .= '&sort=' . $this->_getParam('sort');

                            if ($this->_getParam('order')) {
                                $data['order'] = $this->_getParam('order');
                                $partPaginationUrl .= '&order=' . $this->_getParam('order');
                            }else{
                                $data['order'] = 'asc';
                                $partPaginationUrl .= '&order=asc';
                            }
                    }

                    $partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';

                    if ($this->_getParam('page')){
                            $data['page'] = intval($this->_getParam('page'));
                            $partHeadUrl .= '&page=' . intval($this->_getParam('page'));
                    }else{ //turn on pagination by default
                        $data['page'] = 1;
                    }

                    $this->view->data = $data;
                    $this->view->partHeadUrl = $partHeadUrl;
                    $this->view->partPaginationUrl = $partPaginationUrl;

                    $this->view->suppliers = ($this->_catalogModel->getSuppliers($data)->count() > 0) ? $this->_catalogModel->getSuppliers($data) : null;
                    $this->_helper->viewRenderer('listsupplier');
                    break;
            }
    }

    public function assetAction()
    {
    	$action = $this->_getParam('do');
    
    	switch($action){
    
    		case 'insert':
    
    			$this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'catalogAsset', true);
    
    			$this->view->assetForm = $this->_getAssetForm();
    
    			$request = $this->getRequest();
    
    			if($request->isPost()){
    				if (!$this->_forms['assetForm']->isValid($request->getPost())) {
    					return $this->render('saveasset');
    				}
    				$authService = new Cms_Service_Authentication();
    				$this->_catalogModel->saveAsset($this->_forms['assetForm']->getValues(), $authService->getIdentity()->fullname);
    				$this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Asset has been successfully created!");
    				$this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogAsset', true);
    			}
    
    			$this->_helper->viewRenderer('saveasset');
    			break;
    
    		case 'update':
    
    			$assetId = (int) $this->_getParam('id');
    
    			$this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'catalogAsset', true);
    
    			//if asset id does not exists - redirect to asset access
    			$assetInfo = $this->_catalogModel->getAssetById($assetId);
    			if((null === $assetInfo)){
    				$this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogAsset', true);
    			}
    
    			$this->view->assetForm = $this->_getAssetForm('update', $assetId);
    
    			$request = $this->getRequest();
    
    			if($request->isPost()){
    				
    				if (!$this->_forms['assetForm']->isValid($request->getPost())) {
    					return $this->render('saveasset');
    				}
    				
    				$authService = new Cms_Service_Authentication();
    				$this->_catalogModel->saveAsset($this->_forms['assetForm']->getValues(), $authService->getIdentity()->fullname, $assetInfo);
    				$this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Asset has been successfully updated!");
    
    				if(null !== $this->_helper->redirectUrl()){
    					$this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
    				}else{
    					$this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogAsset', true);
    				}
    				
    			}
    
    			$assetInfo = $assetInfo->toArray();
    			
    			$mysqlDate = new Zend_Date($assetInfo['purchasedDate'], 'yyyy.MM.dd');
    			$assetInfo['purchasedDate'] = $mysqlDate->toString('dd/MM/yyyy');
    			
    			$this->view->assetForm->populate($assetInfo);
    
    			$this->_helper->viewRenderer('saveasset');
    
    			break;
    
    		case 'delete':
    
    			if($this->getRequest()->isPost()){
    
    				$assets = $this->_getParam('selected');
    
    				if ((!empty($assets) && (is_array($assets)))) {
    					foreach ($assets as $asset) {
    						//delete asset
    						$this->_catalogModel->deleteAsset($this->_catalogModel->getAssetById($asset));
    					}
    					$this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Asset(s) has been successfully deleted!");
    				}
    
    				if(null !== $this->_helper->redirectUrl()){
    					$this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
    				}else{
    					$this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogAsset', true);
    				}
    
    			}else{
    				$this->_helper->redirector->gotoRoute(array('do'=>'access'),'catalogAsset', true);
    			}
    
    			break;
    
    		case 'access':
    		default:
    
    			if ($this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->hasMessages()) {
    				$this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->getMessages();
    			}
    
    			if ($this->_helper->flashMessenger->setNamespace('returnMessageWarning')->hasMessages()) {
    				$this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->getMessages();
    			}
    
    			$data = array();
    			$partHeadUrl = '';
    			$partPaginationUrl = '';
    
    			if ($this->_getParam('sort')) {
    				$data['sort'] = $this->_getParam('sort');
    				$partPaginationUrl .= '&sort=' . $this->_getParam('sort');
    
    				if ($this->_getParam('order')) {
    					$data['order'] = $this->_getParam('order');
    					$partPaginationUrl .= '&order=' . $this->_getParam('order');
    				}else{
    					$data['order'] = 'asc';
    					$partPaginationUrl .= '&order=asc';
    				}
    			}
    
    			$partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';
    
    			if ($this->_getParam('page')){
    				$data['page'] = intval($this->_getParam('page'));
    				$partHeadUrl .= '&page=' . intval($this->_getParam('page'));
    			}else{ //turn on pagination by default
    				$data['page'] = 1;
    			}
    
    			$this->view->data = $data;
    			$this->view->partHeadUrl = $partHeadUrl;
    			$this->view->partPaginationUrl = $partPaginationUrl;
    
    			$this->view->assets = ($this->_catalogModel->getAssets($data)->count() > 0) ? $this->_catalogModel->getAssets($data) : null;
    			$this->_helper->viewRenderer('listasset');
    			break;
    	}
    }
    
     protected function _getCategoryForm($formState='create',$categoryId=null)
    {
        
        $this->_forms['categoryForm'] = $this->_catalogModel->getForm('catalogCategoryForm');
        $this->_forms['categoryForm']->setMethod('post');
        
        if($formState == 'update'){
            $this->_forms['categoryForm']->setAction($this->_urlHelper->url(array('do'=>'update','id'=>$categoryId), 'catalogCategory', true));
        }else{
            $this->_forms['categoryForm']->setAction($this->_urlHelper->url(array('do'=>'insert'), 'catalogCategory', true));
        }

        return $this->_forms['categoryForm'];
    }

     protected function _getProductForm($formState='create',$productId=null)
    {
        
        $this->_forms['productForm'] = $this->_catalogModel->getForm('catalogProductForm');
        $this->_forms['productForm']->setMethod('post');
        
        if($formState == 'update'){
            $this->_forms['productForm']->setAction($this->_urlHelper->url(array('do'=>'update','id'=>$productId), 'catalogProduct', true).$this->_helper->redirectUrl(true));
        }else{
            $this->_forms['productForm']->setAction($this->_urlHelper->url(array('do'=>'insert'), 'catalogProduct', true).$this->_helper->redirectUrl(true));
        }

        return $this->_forms['productForm'];
    }

     protected function _getSupplierForm($formState='create',$supplierId=null)
    {

        $this->_forms['supplierForm'] = $this->_catalogModel->getForm('catalogSupplierForm');
        $this->_forms['supplierForm']->setMethod('post');

        if($formState == 'update'){
            $this->_forms['supplierForm']->setAction($this->_urlHelper->url(array('do'=>'update','id'=>$supplierId), 'catalogSupplier', true).$this->_helper->redirectUrl(true));
        }else{
            $this->_forms['supplierForm']->setAction($this->_urlHelper->url(array('do'=>'insert'), 'catalogSupplier', true).$this->_helper->redirectUrl(true));
        }

        return $this->_forms['supplierForm'];
    }
    
     protected function _getAssetForm($formState='create',$assetId=null)
     {
    	$this->_forms['assetForm'] = $this->_catalogModel->getForm('catalogAssetForm');
    	$this->_forms['assetForm']->setMethod('post');
    
    	if($formState == 'update'){
    		$this->_forms['assetForm']->setAction($this->_urlHelper->url(array('do'=>'update','id'=>$assetId), 'catalogAsset', true).$this->_helper->redirectUrl(true));
    	}else{
    		$this->_forms['assetForm']->setAction($this->_urlHelper->url(array('do'=>'insert'), 'catalogAsset', true).$this->_helper->redirectUrl(true));
    	}
    
    	return $this->_forms['assetForm'];
     }

}